4.03 for循环遍历容器
遍历:遍历指的是将一个序列中所有元素逐个获取出来(类似于抓娃娃))
For循环可以对列表、元组等多种容器进行遍历。
#1、直接遍历
j=0 #如不做声明,则会报错
names=["李三","李四","王五","赵六"]
for i in names:
j=j+1
print(j,i)
print("---------")
#2、构造索引
for i in range(0,len(names)):
print(i,names[i])
返回值:
1 李三
2 李四
3 王五
4 赵六
---------
0 李三
1 李四
2 王五
3 赵六
#3、遍历字典
dictA={"name":"张三","年龄":18,"性别":"女"}
for i in dictA:
print(i,dictA[i])
print("------")
for j in dictA:
print(j,dictA.get(j))
返回值:
name 张三
年龄 18
性别 女
------
name 张三
年龄 18
性别 女
#4、遍历集合
num=0
setA={22,33,44,55,66,77}
for i in setA:
num=num+1
print(num,i)
返回值:
1 33
2 66
3 22
4 55
5 44
6 77